﻿using System.Security.Claims;
using System.Text;
using System.Text.Json;
using CoreLib.ConfigOptions;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Options;
using UI.Models;

namespace UI.Api
{
    [Route("api/[controller]")]
    [ApiController]
    public class SystemController : ControllerBase
    {
        private readonly IHttpClientFactory _httpClientFactory;
        private readonly IOptions<IdentityServiceOptions> _identitySvc;

        public SystemController(
            IHttpClientFactory httpClientFactory,
            IOptions<IdentityServiceOptions> identitySvc)
        {
            _httpClientFactory = httpClientFactory ?? throw new ArgumentNullException(nameof(httpClientFactory));
            _identitySvc = identitySvc ?? throw new ArgumentNullException(nameof(identitySvc));
        }

        class TokenModel
        {
            public string access_token { get; set; }
        }

        [HttpPost("login")]
        [AllowAnonymous]
        public async Task<LoginResponse> Login(LoginModel loginModel)
        {
            using (var httpClient = _httpClientFactory.CreateClient())
            {
                var httpContent = new StringContent($"client_id=mobileApprove&grant_type=LoginByService&userName={loginModel.UserName}&password={loginModel.Pwd}&mac={loginModel.Mac}", Encoding.UTF8, "application/x-www-form-urlencoded");
                var response = await httpClient.PostAsync($"{_identitySvc.Value.Host}/connect/token", httpContent);
                if (response.IsSuccessStatusCode)
                {
                    var t = response.Content.ReadAsStringAsync();
                    if (t != null && t.Result != null)
                    {
                        var token = JsonSerializer.Deserialize<TokenModel>(t.Result);

                        if (!string.IsNullOrWhiteSpace(token?.access_token))
                        {
                            //  TODO: 从access_token中解析出claim传入ClaimsIndentity
                            var claimsIdentity = new ClaimsIdentity(new Claim[] { new Claim(ClaimTypes.Name, loginModel.UserName) }, "Basic");
                            await HttpContext.SignInAsync(
                                CookieAuthenticationDefaults.AuthenticationScheme,
                                new System.Security.Claims.ClaimsPrincipal(claimsIdentity));
                            
                            return new LoginResponse { success = true, message = "登录成功，正在跳转..." };
                        }
                    }
                }
                return new LoginResponse { success = false, message = "登录失败，请重试" };
            }
        }

    }
}
